// 管理员绩效评估内容组件
Vue.component('admin-performance-content', {
  data() {
    return {
      performances: [],
      dialogVisible: false,
      editPerformance: { id: '', employee_id: '', score: '', period: '', comments: '' },
      isEdit: false,
      loading: false,
      // 查询条件
      searchName: '',
      searchPeriod: '',
      selectedDepartment: '',
      departments: [],
      employees: [],
      // 分页功能
      currentPage: 1,
      pageSize: 10,
      totalRecords: 0
    };
  },
  async mounted() {
    await this.loadDepartments();
    await this.loadPerformances();
  },
  template: `
    <div style="padding: 32px; width: 100%; box-sizing: border-box;">
      <el-card shadow="hover" style="width: 100%;">
        <div style="font-size: 22px; font-weight: bold; margin-bottom: 18px;">绩效评估</div>
        
        <!-- 查询控件 -->
        <div style="display: flex; align-items: center; margin-bottom: 12px;">
          <el-input v-model="searchName" placeholder="搜索姓名" style="width: 120px; margin-right: 8px;" size="small" clearable></el-input>
          <el-select v-model="selectedDepartment" placeholder="选择部门" style="width: 120px; margin-right: 8px;" size="small" clearable>
            <el-option v-for="dept in departments" :key="dept.id" :label="dept.name" :value="dept.id"></el-option>
          </el-select>
          <el-date-picker v-model="searchPeriod" type="month" placeholder="按评估周期查询" style="width: 180px; margin-right: 8px;" value-format="yyyy-MM" size="small" clearable></el-date-picker>
          <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
          <el-button size="small" @click="handleReset">重置</el-button>
          <el-button type="primary" size="small" style="margin-left: auto;" @click="openAddDialog">添加评估</el-button>
        </div>
        
        <el-table :data="performances" style="width: 100%; margin-top: 10px;" v-loading="loading">
          <el-table-column prop="employee_name" label="姓名" width="120"></el-table-column>
          <el-table-column prop="department_name" label="部门" width="120"></el-table-column>
          <el-table-column prop="score" label="分数" width="100"></el-table-column>
          <el-table-column prop="period" label="评估周期" width="120"></el-table-column>
          <el-table-column prop="comments" label="评语" min-width="200"></el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
              <el-button type="text" size="mini" @click="deletePerformance(scope.row)" style="color: #F56C6C;">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页组件 -->
        <div style="margin: 18px 0 0; text-align: right;">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalRecords"
            :page-size="pageSize"
            :current-page.sync="currentPage"
            @current-change="handlePageChange"
          ></el-pagination>
        </div>
        
        <el-dialog :title="isEdit ? '编辑评估' : '添加评估'" :visible.sync="dialogVisible" width="400px">
          <el-form :model="editPerformance" label-width="80px">
            <el-form-item label="员工">
              <el-select v-model="editPerformance.employee_id" placeholder="请选择员工" style="width: 100%;">
                <el-option 
                  v-for="emp in employees" 
                  :key="emp.id" 
                  :label="emp.name" 
                  :value="emp.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="分数">
              <el-input v-model.number="editPerformance.score" type="number" placeholder="请输入分数" style="width: 100%;"></el-input>
            </el-form-item>
            <el-form-item label="评估周期">
              <el-input v-model="editPerformance.period" placeholder="请输入评估周期（如：2024-Q1）" style="width: 100%;"></el-input>
            </el-form-item>
            <el-form-item label="评语">
              <el-input v-model="editPerformance.comments" placeholder="请输入评语" style="width: 100%;"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="savePerformance">确 定</el-button>
          </span>
        </el-dialog>
      </el-card>
    </div>
  `,
  methods: {
    // 获取部门名称的辅助方法
    getDepartmentName(departmentId) {
      const dept = this.departments.find(d => d.id === departmentId);
      return dept ? dept.name : '未知部门';
    },
    
    // 加载部门数据
    async loadDepartments() {
      try {
        const response = await departmentAPI.getDepartments();
        this.departments = response.data.departments || [];
      } catch (error) {
        console.error('加载部门数据失败:', error);
        this.$message.error('加载部门数据失败');
      }
    },
    
    // 加载员工数据
    async loadEmployees() {
      try {
        const response = await employeeAPI.getEmployees();
        this.employees = response.data.employees || [];
      } catch (error) {
        console.error('加载员工数据失败:', error);
        this.$message.error('加载员工数据失败');
      }
    },
    
    // 加载绩效数据
    async loadPerformances() {
      this.loading = true;
      try {
        const params = {
          page: this.currentPage,
          page_size: this.pageSize,
          search: this.searchName || undefined,
          department_id: this.selectedDepartment || undefined,
          period: this.searchPeriod || undefined
        };
        
        const response = await performanceAPI.getPerformances(params);
        this.performances = response.data.performances || [];
        this.totalRecords = response.data.pagination ? response.data.pagination.total : response.data.total || 0;
      } catch (error) {
        console.error('加载绩效数据失败:', error);
        this.$message.error('加载绩效数据失败');
      } finally {
        this.loading = false;
      }
    },
    
    handleSearch() {
      this.currentPage = 1;
      this.loadPerformances();
    },
    
    handleReset() {
      this.searchName = '';
      this.selectedDepartment = '';
      this.searchPeriod = '';
      this.currentPage = 1;
      this.loadPerformances();
    },
    
    handlePageChange(page) {
      this.currentPage = page;
      this.loadPerformances();
    },
    
    async openAddDialog() {
      this.isEdit = false;
      this.editPerformance = { id: '', employee_id: '', score: '', period: '', comments: '' };
      await this.loadEmployees();
      this.dialogVisible = true;
    },
    
    async openEditDialog(row) {
      this.isEdit = true;
      this.editPerformance = Object.assign({}, row);
      await this.loadEmployees();
      this.dialogVisible = true;
    },
    
    async savePerformance() {
      if (!this.editPerformance.employee_id || !this.editPerformance.score || !this.editPerformance.period) {
        this.$message.error('请填写完整信息');
        return;
      }
      
      try {
        if (this.isEdit) {
          await performanceAPI.updatePerformance(this.editPerformance.id, this.editPerformance);
          this.$message.success('评估信息已更新');
        } else {
          await performanceAPI.createPerformance(this.editPerformance);
          this.$message.success('评估已添加');
          this.currentPage = 1;
        }
        this.dialogVisible = false;
        this.loadPerformances();
      } catch (error) {
        console.error('保存绩效评估失败:', error);
        this.$message.error(error.message || '保存绩效评估失败');
      }
    },
    
    async deletePerformance(row) {
      this.$confirm('确定要删除该评估吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await performanceAPI.deletePerformance(row.id);
          this.$message.success('评估已删除');
          
          // 删除后检查当前页是否还有数据
          const totalPages = Math.ceil((this.totalRecords - 1) / this.pageSize);
          if (this.currentPage > totalPages && totalPages > 0) {
            this.currentPage = totalPages;
          }
          
          this.loadPerformances();
        } catch (error) {
          console.error('删除绩效评估失败:', error);
          this.$message.error(error.message || '删除绩效评估失败');
        }
      });
    }
  }
});